// 引入axios
import axios from "axios";
import store from "../vuex/store";
import router from "../router";
import { Message } from "element-ui";

const Tip = msg => {
    Message({
        showClose: true,
        message: msg,
        type: "warning"
    })
}

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/// 创建axios实例
const http = axios.create({
    //请求接口
    baseURL: cfg.baseURL,
    //超时设置
    timeout: 1000 * 30,
    //请求头设置
    headers: {
        "Content-Type": "application/json;charset=UTF-8",
    }
});

http.interceptors.request.use(
    config => {
        config.headers["Authorization"] = "Bearer " + localStorage.getItem("token");
        return config;
    },
    error => Promise.error(error)
);

const errorHandle = status => {
    switch (status) {
        case 401:
            router.replace({
                path: '/login',
            });
            break;
        case 403:
            Tip("登录过期，请重新登录");
            localStorage.removeItem("token");
            store.commit("login", false);
            router.replace({
                path: '/login',
            });
        case 404:
            Tip("请求的资源不存在");
        default:
            break;
    }
}

http.interceptors.response.use(
    res => (res.status === 200 ? Promise.resolve(res) : Promise.reject(res)),
    error => {
        const { response } = error;
        if (response) {
            errorHandle(response.status, response.data.message);
            return Promise.reject(response);
        }
    }
);

export default http;